// MessageNotificationDao.java
package net.web.dao;

import net.web.common.utils.JdbcUtils;
import net.web.entity.MessageNotification;

import java.util.List;
import java.util.ArrayList;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;

public class MessageNotificationDao {
    public boolean insert(MessageNotification notification) {
        String sql = "INSERT INTO message_notification (recipient_id, sender_id, blog_id, message_type) VALUES (?,?,?,?)";
        int rows = JdbcUtils.executeUpdate(sql, notification.getRecipientId(), notification.getSenderId(), notification.getBlogId(), notification.getMessageType());
        return rows > 0;
    }

    public List<MessageNotification> getNotificationsByUserId(int userId) {
        String sql = "SELECT * FROM message_notification WHERE recipient_id = ? ORDER BY created_at DESC";
        return JdbcUtils.executeQuery(MessageNotification.class, sql, userId);
    }

    public boolean markAsRead(int notificationId) {
        String sql = "UPDATE message_notification SET is_read = true WHERE id = ?";
        return JdbcUtils.executeUpdate(sql, notificationId) > 0;
    }

    public List<MessageNotification> getUnreadNotificationsByUserId(int userId) {
        List<MessageNotification> list = new ArrayList<>();
        String sql = "SELECT * FROM message_notification WHERE recipientid = ? AND isread = 0 ORDER BY createdat DESC";
        try (Connection conn = JdbcUtils.getConnection();
             PreparedStatement pstmt = conn.prepareStatement(sql)) {
            pstmt.setInt(1, userId);
            ResultSet rs = pstmt.executeQuery();
            while (rs.next()) {
                MessageNotification mn = new MessageNotification();
                mn.setId(rs.getInt("id"));
                mn.setRecipientId(rs.getInt("recipientid"));
                mn.setSenderId(rs.getInt("senderid"));
                mn.setBlogId(rs.getInt("blogid"));
                mn.setMessageType(rs.getString("messagetype"));
                mn.setIsRead(rs.getBoolean("isread"));
                mn.setCreatedAt(rs.getTimestamp("createdat"));
                list.add(mn);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return list;
    }
}